﻿using System;
using System.Linq;
using AmoExtensions;
using Args;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace SsasPartitionManager
{
    /*
     * SSAS Partition Manager
     * Written by Dr. John Tunnicliffe of Decision Analytics, April 2015
     * eMail: john@decision-analytics.co.uk 
     * http://www.decision-analytics.co.uk/
     * https://www.linkedin.com/in/drjohntunnicliffe
     */
    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);   

        static void Main(string[] args)
        {
            log.Debug("SsasPartitionManager starting");
            try
            {
                // the following line assigns all the command-line options to the varibles in the command-line options object
                var cmdOptions = Args.Configuration.Configure<SsasPartitionManagerOptions>().CreateAndBind(args);

                // if the option was not passed on the command-line, then read it from the config file
                if (cmdOptions.ServerType.IsNullOrEmptyOrWhitespace())
                    cmdOptions.ServerType = SsasPartitionManager.Properties.Settings.Default.ServerType;

                if (cmdOptions.ConfigDatabaseConnectionString.IsNullOrEmptyOrWhitespace())
                    cmdOptions.ConfigDatabaseConnectionString = SsasPartitionManager.Properties.Settings.Default.configDatabaseConnectionString;
                
                if (cmdOptions.Sql1ToListServers.IsNullOrEmptyOrWhitespace())
                    cmdOptions.Sql1ToListServers = SsasPartitionManager.Properties.Settings.Default.sqlListServers;

                if (cmdOptions.Sql2ToListPartitions.IsNullOrEmptyOrWhitespace())
                    cmdOptions.Sql2ToListPartitions = SsasPartitionManager.Properties.Settings.Default.sqlListPartitions;

                // call the partition manager, passing in the command-line options  which we set up above
                var ssasPartitionManager = new AmoExtensions.SsasPartitionManager();
                ssasPartitionManager.DoPartitionManagement(cmdOptions);
            }
            catch (System.Data.SqlClient.SqlException sqlex)
            {
                string msg = string.Format("Fatal database configuration error encountered: {0}", sqlex.Message);
                log.Fatal(msg);
                log.Debug("SsasPartitionManager ending");
                throw new Exception(msg);
            }
            catch (Exception ex)
            {
                string msg = string.Format("Fatal config error occurred: {0}", ex.Message);
                log.Fatal(msg);
                log.Debug("SsasPartitionManager ending");
                throw new Exception(msg);
            }
            log.Debug("SsasPartitionManager ending");
        }

        
    }

  

}
